/*公用函数*/

// cookie操作
function cookieClass(){
	// 写操作
	function setCookie(name,value){
		localStorage.setItem(name,JSON.stringify(value));
	}

	// 读操作
	function getCookie(name){
		return JSON.parse(localStorage.getItem(name));
	}

	// 删除cookie
	function delCookie(name){
		localStorage.removeItem(name);
	}

	// 清空cookie
	function clearCookie(){
	    localStorage.clear();
	}

	// 对外接口
	return {
		set: setCookie,
		get: getCookie,
		del: delCookie,
		clear: clearCookie
	};
}

// 设置ajax参数
function ajax(options){
	var cookieDom = cookieClass();
	var baseUrl = process.env.API_ROOT;
	var data = {
			url: '/',
			method: 'post',
			baseURL: baseUrl,
			headers: {'token': cookieDom.get('token'),'Content-Type': 'application/json,charset=utf-8'},
			data: null,
			timeout: 5000,
			responseType: 'json',
			success: function(){
				console.log('success');
			},
			fail: function(){
				console.log('error');
			},
			complete: function(){
				console.log('complete');
			}
		}

	options.data = JSON.stringify(options.data);
	data = Object.assign(data, options);

	var that = data.that;
	that.$http({
			url: data.url,
			method: data.method,
			baseURL:data.baseURL,
			headers: data.headers,
			data: data.data,
			timeout: data.timeout,
			responseType: data.responseType
		})
	.then(function(res){
		var resData = res.data;
		if(resData.code === 200){
			data.success(resData);
		} else if (resData.code === 400){
			data.fail(resData.msg);
		} else if (resData.code === 100){
			that.$Message.info({
				content: resData.msg,
				onClose: function(){
					var cookie = that.$util.cookie();
		            cookie.del('token');
		            cookie.del('name');
		            that.$router.push({
	                                name: 'login',
	                                params: {}
	                            })
				}
			});
		} else if (resData.code === 101){
			that.$Message.info(resData.msg);
		} else if (resData.code === 404){
			that.$Message.info(resData.msg);
		} else {}
		
		data.complete();
	})
	.catch(function(err){
		console.log(err);
		that.$Message.info('系统繁忙！');
		data.complete();
	});
}

/* * 对象数据转为树结构 * data：带转换成树形结构的对象数组 * attributes：对象属性 */
function arrToTree(data, attributes){
     function treeObj(originObj){
			//对象深拷贝
			let obj ={};
			for (var key in originObj){
				var val =originObj[key];
				obj[key] = typeof val === 'object' ? arguments.callee(val):val;
			}
			//对象新增children键值，用于存放子树
			obj['children'] = [];
			return obj;
	}
 
	//data：带转换成树形结构的对象数组
	//attributes：对象属性
	function toTreeData (data, attributes) {
	  let resData = data;
	  let tree = [];
	 
	 //找寻根节点
	  for (let i = 0; i < resData.length; i++) {
	    if (resData[i][attributes.parentId] === 0) {
	      tree.push( treeObj(resData[i]) );
	      resData.splice(i, 1);
	      i--;
	    }
	  }
	 
	  //找寻子树
	  function run(chiArr) {
	    if (resData.length !== 0) {
	      for (let i = 0; i < chiArr.length; i++) {
	        for (let j = 0; j < resData.length; j++) {
	          if (chiArr[i][attributes.id] === resData[j][attributes.parentId]){
	            let obj = treeObj(resData[j]);
	            chiArr[i].children.push(obj);
	            resData.splice(j, 1);
	            j--;
	          }
	        }
	        run(chiArr[i].children);
	      }
	    }
	  }

	  run(tree);
	 
	  return tree;
	 
	}

	return toTreeData(data, attributes);
}

// 获取可视窗口高度
function getClientHeight(){
  var clientHeight=0;
  if(document.body.clientHeight&&document.documentElement.clientHeight)
  {
  var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }
  else
  {
  var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }
  return clientHeight;
}

// 深拷贝
function deepCopy(obj){
    if(typeof obj != 'object'){
        return obj;
    }
    var newobj = {};
    for ( var attr in obj) {
        newobj[attr] = deepCopy(obj[attr]);
    }
    return newobj;
}

// 浅拷贝
function copy(obj){
    var newobj = {};
    for ( var attr in obj) {
        newobj[attr] = obj[attr];
    }
    return newobj;
}

const util = {
	ajax: ajax,
	cookie: cookieClass,
	arrToTree: arrToTree,
	getClientHeight: getClientHeight,
	deepCopy: deepCopy,
	copy: copy,
}
export default util;